package com.example.myapplication.A_Test0515;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.R;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class Fg_1 extends Fragment {
    String TAG = "a====a";


    private RecyclerView rv;
    private ListView lv;
    private List<Page> pageList;
    private RecyclerAdapter recyclerAdapter;
    private PageAdapter pageAdapter;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            List<GsonJson.ResultBean.DataBean> list = (List<GsonJson.ResultBean.DataBean>) msg.obj;
            Log.e(TAG, "handleMessage: "+list.get(1).getAuthor_name() );
            pageAdapter=new PageAdapter(list,getContext());
            lv.setAdapter(pageAdapter);
        }
    };

    public Fg_1() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fg_1, container, false);
        initData();
        rv = view.findViewById(R.id.rv);
        lv = view.findViewById(R.id.lv_1);

        recyclerAdapter = new RecyclerAdapter(pageList, getContext());
        rv.setAdapter(recyclerAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv.setLayoutManager(layoutManager);
        recyclerAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                recyclerAdapter.setHua(position);

            }
        });
        getJsonData();



        return view;
    }

    private void getJsonData() {
        new Thread() {
            @Override
            public void run() {
                try {
                    String jsonData = OkHttpUtils.connectServer("");
                    Gson gson = new Gson();
                    GsonJson myJson = gson.fromJson(jsonData, GsonJson.class);
                    List<GsonJson.ResultBean.DataBean> list = myJson.getResult().getData();
                    Message message = new Message();
                    message.obj = list;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    public void initData() {
        pageList = new ArrayList<>();
        pageList.add(new Page("关注", 0));
        pageList.add(new Page("推荐", 1));
        pageList.add(new Page("十九大", 2));
        pageList.add(new Page("热点", 3));
        pageList.add(new Page("科技", 4));
        pageList.add(new Page("视频", 5));
    }


    public static class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
        private List<Page> PagesList;
        private int layoutPosition; //记录当前点击位置
        private int HuaPosition;
        private Context context;

        //点击事件接口私有属性
        private OnItemClickListener onItemClickListener = null;

        //setter方法
        public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.onItemClickListener = onItemClickListener;
        }

        //点击事件回调接口
        public interface OnItemClickListener {
            void onItemClick(View view, int position);
        }


        /**
         * 构造函数,用于把要展示的数据源传入,并赋予值给全局变量
         *
         * @param PagesList
         */
        public RecyclerAdapter(List<Page> PagesList, Context context) {
            this.PagesList = PagesList;
            this.context = context;
        }

        /**
         * 定义内部类ViewHolder,并继承RecyclerView.ViewHolder。
         * 传入的View参数通常是RecyclerView子项的最外层布局。
         */

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_page_name;

            public ViewHolder(View view) {
                super(view);
                tv_page_name = view.findViewById(R.id.tv_page_name);
            }
        }

        /**
         * onCreateViewHolder()用于创建ViewHolder实例,并把加载的布局传入到构造函数去,再把ViewHolder实例返回
         *
         * @param parent
         * @param viewType
         * @return
         */
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.page_item, parent, false);
            ViewHolder holder = new ViewHolder(view);
            //实现点击效果
            //holder.itemView.setTag(viewType);
            return holder;
        }

        /**
         * onBindViewHolder()则是用于对子项的数据进行赋值,
         * 会在每个子项被滚动到屏幕内时执行。position得到当前项的User实例。
         *
         * @param holder
         * @param position
         */
        @Override
        public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
            Page page = PagesList.get(position);
            holder.tv_page_name.setText(page.getName());
            holder.itemView.setTag(position);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //程序执行到此，会去执行具体实现的onItemClick()方法
                    if (onItemClickListener != null) {
                        //获取当前点击的位置
                        layoutPosition = holder.getLayoutPosition();
                        notifyDataSetChanged();
                        onItemClickListener.onItemClick(holder.itemView, (int) holder.itemView.getTag());
                        //onItemClickListener.onItemClick(v);
                    }
                }
            });
            //更改状态
            if (position == layoutPosition) {
                holder.tv_page_name.setTextColor(Color.parseColor("#ff0000"));
            } else {
                holder.tv_page_name.setTextColor(Color.parseColor("#000000"));
            }
            if (position == HuaPosition) {
                holder.tv_page_name.setTextColor(Color.parseColor("#ff0000"));
            } else {
                holder.tv_page_name.setTextColor(Color.parseColor("#000000"));
            }
        }

        /**
         * getItemCount()返回RecyclerView的子项数目
         *
         * @return
         */
        @Override
        public int getItemCount() {
            return PagesList.size();
        }

        public void setHua(int HuaPosition) {
            this.HuaPosition = HuaPosition;
        }

    }


    class PageAdapter extends BaseAdapter {
        public List<GsonJson.ResultBean.DataBean> list;
        Context context;
        int selectedPosition;

        public PageAdapter(List<GsonJson.ResultBean.DataBean> list, Context context) {
            this.list = list;
            this.context = context;
        }

        @Override
        public int getCount() {
            return list != null ? list.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void clearSelection(int position) {
            selectedPosition = position;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View v = null;
            if (view != null) {
                v = view;
            } else {
                v = LayoutInflater.from(context).inflate(R.layout.item_list, viewGroup, false);
            }

            ViewHolder holder = (ViewHolder) v.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.imageView = v.findViewById(R.id.iv);
                holder.tv1 = v.findViewById(R.id.tv_1);
                holder.tv2 = v.findViewById(R.id.tv_2);
                holder.tv3 = v.findViewById(R.id.tv_3);
            }
            Bitmap bitmap= setPosterBitmap(list.get(i).getThumbnail_pic_s());
            holder.imageView.setImageBitmap(bitmap);
            //holder.imageView.setImageBitmap(list.get(i));
            holder.tv1.setText(list.get(i).getAuthor_name());
            holder.tv2.setText(list.get(i).getCategory());
            holder.tv3.setText(list.get(i).getDate());
            v.setTag(holder);
            return v;
        }

        private class ViewHolder {
            private ImageView imageView;
            private TextView tv1;
            private TextView tv2;
            private TextView tv3;
        }
    }

    Bitmap setPosterBitmap(String url) {
        final Bitmap[] mBitmap = new Bitmap[1];
        Picasso.get().load(url).into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                mBitmap[0] = bitmap;
            }

            @Override
            public void onBitmapFailed(Exception e, Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        });
        return mBitmap[0];
    }

    @Override
    public void onResume() {
        super.onResume();
        getJsonData();
    }
}
